package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.Calendar;

/**
 * ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or
 * datetime expression, and expr2 is a time expression.
 */
public class AddTime extends ScalarFunction {

    @SuppressWarnings("deprecation")

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        java.sql.Timestamp timestamp = Type.TimestampType.convert(args[0]);
        Calendar cal = Calendar.getInstance();
        cal.setTime(timestamp);

        java.sql.Time time = Type.TimeType.convert(args[1]);

        cal.add(Calendar.HOUR_OF_DAY, time.getHours());
        cal.add(Calendar.MINUTE, time.getMinutes());
        cal.add(Calendar.SECOND, time.getSeconds());
        Type type = getReturnType();
        return type.convert(cal.getTime());
    }

    public Type getReturnType() {
        Type type = getFirstArgType();
        if (type == Type.DateType) {
            return Type.TimestampType;
        }

        return type;
    }

    public String[] getFunctionNames() {
        return new String[]{"ADDTIME"};
    }
}
